package com.maple.admin.user.service.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.maple.admin.misc.paging.dto.PagingParamsDTO;
import com.maple.admin.security.shiro.util.CredentialsGenerator;
import com.maple.admin.user.dao.IAccountDAO;
import com.maple.admin.user.dto.UserDTO;
import com.maple.admin.user.service.IAccountService;

/**
 * account maintenance
 * @author luobenyu
 *
 */
@Service
public class IAccountServiceImpl implements IAccountService {
	
	@Autowired
	private IAccountDAO userDAO;

	public IAccountServiceImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public UserDTO queryUserByLoginName(String userName) throws IndexOutOfBoundsException {
		// TODO Auto-generated method stub
		return userDAO.queryUserByLoginName(userName);
	}

	@Override
	public List<UserDTO> queryPaginatedUsers(PagingParamsDTO paging) {
		// TODO Auto-generated method stub
		Integer p = paging.getPage();
		// fix records index
		if(p <= 1){
			paging.setPage(0);
		}
		return userDAO.queryPaginatedUsers(paging);
	}

	@Override
	public List<UserDTO> queryAllUsers() {
		// TODO Auto-generated method stub
		return userDAO.queryAllUsers();
	}

	@Override
	public Boolean checkDuplicated(String userName) {
		// TODO Auto-generated method stub
		return userDAO.checkDuplicated(userName);
	}

	@SuppressWarnings("static-access")
	@Override
	public UUID createUser(UserDTO newUser) {
		// TODO Auto-generated method stub
		CredentialsGenerator generator = CredentialsGenerator.getInstance();
		String originPassword = newUser.getUserPwd();
		Map<String,Object> saltedInfo = generator.encryptPassword(originPassword);
		// set encrypted password and salt
		newUser.setUserPwd((String) saltedInfo.get("saltedPassword"));
		newUser.setUserSalt((String) saltedInfo.get("salt"));
		// create 
		return userDAO.createUser(newUser);
	}

}
